const bcrypt = require('bcryptjs');
const decrypt = require('./decrypt')
const getToken = require('./getToken')
const db = require("../../database");
const writeLogs = require('./writeLogs');

module.exports = (req, res) => {
    let {username, inputPass} = req.body;

    const loginMethod = username.includes('@') ? 'mail' : 'username';
    const sql = `select username, password, status, verErrStartDate, friends, messages from users where ${loginMethod} = ?`;
    db.query(sql, username, (err, data) => {
        if (err) return res.cc(err)
        if (data.length === 0) return res.cc('用户名不存在')
        const {password, status, verErrStartDate, friends, messages} = data[0];
        if (loginMethod === 'mail') username = data[0].username;
        if (status !== 0) {
            // 时间间隔大于1天
            if (Date.now() - verErrStartDate < 864e5) {
                return res.cc('账号已被封禁')
            } else {
                db.query(`update users set status = 0, chance = 3 where username = ${username}`, (err) => {
                    if (err) writeLogs('err', { err })
                })
            }
        }
        const decrypted = decrypt(inputPass);
        if (bcrypt.compareSync(decrypted, password)) {
            writeLogs('login', {username});
            res.cc({token: getToken(username), username, friends, messages}, 0);
        } else {
            res.cc('校验未通过', 2);
        }
    })
}